const wxpay = require('../../utils/pay.js')
const app = getApp()
const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')

Page({
  data: {
    //0:待付款 1:已付款 2:已发货 3:已收货 4:退款中 5:订单关闭
    // statusType: ["全部", "待付款", "待发货", "已发货", "已收货", "退款中"],
    // statusType: ["待付款", "待取货", "已完成", "退款中"],
    // statusType: ["待付款", "待取货", "已完成"],
    statusType: [
      { type: "待付款", id: 0 }, 
      { type: "待取货", id: 2 },
      {type: "已完成", id: 3},
      {type: "退款中", id: 4}
    ],
    hasRefund: false,
    currentType: 0,
    tabClass: ["", "", "", "", ""],
    pageNo:1,
    showCertificateCover:false,
    pingZheng:'',
  },
  toSearchPage() {
    wx.navigateTo({
      url: '/pages/search/search?type=searchOrder',
    })
  },
  move() { },
  closeCover(){
    this.setData({
      showCertificateCover: false,
    })
  },
  showCertificate(e){
    let pingZheng = e.currentTarget.dataset.pingzheng;
    this.setData({
      showCertificateCover: true,
      pingZheng: pingZheng,
    })
  },
  toDeatil(e){
    let id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/pages/order-details/index?id=" + id
    })

  },
  copyCertificateNo(){
    app.copyText(this.data.pingZheng);
    this.closeCover();
  },
  statusTap: function(e) {
    const curType = e.currentTarget.dataset.index;
    // this.data.currentType = curType
    if (curType != this.data.currentType){
      this.setData({
        currentType: curType,
        pageNo: 1,
      });
      this.onShow();
      let postData = {
        orderStatus: this.data.currentType,
        pageNum: this.data.pageNo,
        pageSize:10
      };
      this.getLists(postData);
      
    }
  },
  cancelOrderTap: function(e) {
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确定要取消该订单吗？',
      content: '',
      success: function(res) {
        if (res.confirm) {
          WXAPI.orderClose(orderId).then(function(res) {
            if (res.retCode === '200') {
              that.onShow();
            }
          })
        }
      }
    })
  },
  refundApply (e) {
    // 申请售后
    const orderId = e.currentTarget.dataset.id;
    const amount = e.currentTarget.dataset.amount;
    wx.navigateTo({
      url: "/pages/order/refundApply?id=" + orderId + "&amount=" + amount
    })
  },
  confirm(e){
    //确认收货
    const orderId = e.currentTarget.dataset.id;
    const _this = this
    WXAPI.confirmRecv({orderNo:orderId}).then((res) => {
      if(res.retCode === '200'){
        wx.showToast({
          title: '操作成功',
          icon: 'none'
        })
        _this.onShow()
      }else{
        wx.showToast({
          title: res.retMsg,
          icon: 'none'
        })
        _this.onShow()
      }
    })
  },
  toPayTap: function(e) {
    // 防止连续点击--开始
    if (this.data.payButtonClicked) {
      wx.showToast({
        title: '休息一下~',
        icon: 'none'
      })
      return
    }
    this.data.payButtonClicked = true
    setTimeout(() => {
      this.data.payButtonClicked = false
    }, 3000)  // 可自行修改时间间隔（目前是3秒内只能点击一次支付按钮）
    // 防止连续点击--结束
    const that = this;
    const orderId = e.currentTarget.dataset.id;
    let money = e.currentTarget.dataset.money;
    // const needScore = e.currentTarget.dataset.score;
    console.log("pay data orderId=", orderId)
    const postData = {
      orderNo: orderId
    }
    WXAPI.userAmount(postData).then(function(res) {
      console.log('res--0-',res)
      if (res.retCode === '200') {
        // 增加提示框
        // if (res.data.score < needScore) {
        //   wx.showToast({
        //     title: '您的积分不足，无法支付',
        //     icon: 'none'
        //   })
        //   return;
        // }
        let _msg = '订单金额: ' + money +' 元'
        // if (res.data.balance > 0) {
        //   _msg += ',可用余额为 ' + res.data.balance +' 元'
        //   if (money - res.data.balance > 0) {
        //     _msg += ',仍需微信支付 ' + (money - res.data.balance) + ' 元'
        //   }          
        // }
        // if (needScore > 0) {
        //   _msg += ',并扣除 ' + money + ' 积分'
        // }
        // money = money - res.data.balance

        const payData = res.data
        wx.showModal({
          title: '请确认支付',
          content: _msg,
          confirmText: "确认支付",
          cancelText: "取消支付",
          success: function (res) {
            console.log(res);
            if (res.confirm) {
              // 发起支付
              // const temp = {"timeStamp":"1573994781","package":"prepay_id=wx172046215593305abef413dc1347082600","appId":"wxa5b625b63b55a186","sign":"922430F1D1E0BEE96FDA538947439D55","signType":"MD5","nonceStr":"2yqds571jg5d8ic4xmu7rbyi32b2g6y3"}

      wx.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: 'MD5',
        paySign: payData.sign,
        fail: function (aaa) {
          wx.showToast({
            title: '支付失败:' + aaa
          })
        },
        success: function () {
          // 保存 formid
          // WXAPI.addTempleMsgFormid(wx.getStorageSync('token'), 'pay', res.data.prepayId)
          // 提示支付成功
          wx.showToast({
            title: '支付成功'
          })
          that.onShow();
          // wx.redirectTo({
          //   url: redirectUrl
          // });
        }
      })
            } else {
              console.log('用户点击取消支付')
            }
          }
        });
      } else {
        wx.showModal({
          title: '错误',
          content: '无法获取用户资金信息',
          showCancel: false
        })
      }
    })
  },
  _toPayTap: function (orderId, money){
    const _this = this
    if (money <= 0) {
      // 直接使用余额支付
      WXAPI.orderPay(wx.getStorageSync('token'), orderId).then(function (res) {
        _this.onShow();
      })
    } else {
      wxpay.wxpay('order', money, orderId, "/pages/order-list/index");
    }
  },
  onLoad: function(options) {
    if (options && options.type) {
      if (options.type == 99) {
        this.setData({
          hasRefund: true,
          currentType: options.type
        });
      } else {
        this.setData({
          hasRefund: false,
          currentType: options.type
        });
      }      
    }
    // 屏蔽分享
    wx.hideShareMenu();
  },
  onReady: function() {
    // 生命周期函数--监听页面初次渲染完成

  },
  getOrderStatistics: function() {
    var that = this;
    WXAPI.orderStatistics(wx.getStorageSync('token')).then(function(res) {
      if (res.code == 0) {
        var tabClass = that.data.tabClass;
        if (res.data.count_id_no_pay > 0) {
          tabClass[0] = "red-dot"
        } else {
          tabClass[0] = ""
        }
        if (res.data.count_id_no_transfer > 0) {
          tabClass[1] = "red-dot"
        } else {
          tabClass[1] = ""
        }
        if (res.data.count_id_no_confirm > 0) {
          tabClass[2] = "red-dot"
        } else {
          tabClass[2] = ""
        }
        if (res.data.count_id_no_reputation > 0) {
          tabClass[3] = "red-dot"
        } else {
          tabClass[3] = ""
        }
        if (res.data.count_id_success > 0) {
          //tabClass[4] = "red-dot"
        } else {
          //tabClass[4] = ""
        }

        that.setData({
          tabClass: tabClass,
        });
      }
    })
  },
  onShow: function() {
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        this.doneShow();
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/my/index"
              })
            } else {
              wx.navigateBack()
            }
          }
        })
      }
    })
  },
  doneShow: function() {
    // 获取订单列表

    const { userNo, merShopInfos } = wx.getStorageSync('curUserInfo')

    var that = this;
    let postData = {
      orderStatus: this.data.currentType,
      // orderStatus: '',
      pageNum: this.data.pageNo,
      pageSize: 10,
      userNo,
      shopNo: merShopInfos[0].shopNo
    };
    // this.getOrderStatistics();
    // WXAPI.orderList(postData).then(function(res) {
    //   if (res.retCode == "200") {
    //     // 获取当前时间戳
    //     let timestamp = Date.parse(new Date());
    //     let resList = res.data.list
    //     for (let item of resList){
    //       // 获取订单截止时间戳，并与当前时间戳相减
    //       item.time = Date.parse(item.overTime) - timestamp;
    //       item.timeData={};
    //     }
    //     that.setData({
    //       orderList: resList,
    //      // logisticsMap: res.data.logisticsMap,
    //      // goodsMap: res.data.goodsMap
    //     });
    //   } else {
    //     that.setData({
    //       orderList: null,
    //       logisticsMap: {},
    //       goodsMap: {}
    //     });
    //   }
    // })
    that.getLists(postData);
  },
  // 获取列表数据
  getLists(postData){
    let that = this;
    WXAPI.shopOrderList(postData).then(function (res) {
      if (res.retCode == "200") {
        // 获取当前时间戳
        let timestamp = Date.parse(new Date());
        let resList = res.data.list
        for (let item of resList) {
          // 获取订单截止时间戳，并与当前时间戳相减
          item.time = Date.parse(item.overTime) - timestamp;
          item.timeData = {};
        }
        that.setData({
          orderList: resList,
          // logisticsMap: res.data.logisticsMap,
          // goodsMap: res.data.goodsMap
        });
      } else {
        that.setData({
          orderList: null,
          logisticsMap: {},
          goodsMap: {}
        });
      }
    })
  },
  onHide: function() {
    // 生命周期函数--监听页面隐藏

  },
  onUnload: function() {
    // 生命周期函数--监听页面卸载

  },
  onPullDownRefresh: function() {
    // 页面相关事件处理函数--监听用户下拉动作

  },
  onReachBottom: function() {
    // 页面上拉触底事件的处理函数
    var that = this;
    let pageNoNew = this.data.pageNo + 1;
    that.setData({
      pageNo: pageNoNew,
    })
    let postData = {
      orderStatus: this.data.currentType,
      pageNum: pageNoNew,
      pageSize: 10
    };
    that.getLists(postData);
  }
})